package com.soft.controller;


import java.math.BigDecimal;
import java.util.Date;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.soft.entity.Orderlist;
import com.soft.service.OrderlistService;
import com.soft.service.OrderlistService.DateFormatUtil;
@RestController
@RequestMapping("/orderlist")
public class OrderlistController {
    
    @Autowired
    private OrderlistService orderlistService;
    
    /**
     * 添加订单（时间自动获取当前系统时间）
     * @param userId 用户ID
     * @param deskId 桌号ID
     * @param orderlistStatus 订单状态
     * @param employeeId 员工ID
     * @param orderlistTotalprice 订单总价
     * @param storeId 门店ID
     * @return 操作结果消息，成功返回"添加成功"，失败返回"添加失败"
     */
    @RequestMapping("/addorderlist")
    public String addOrderlist(
            @RequestParam Long userId,
            @RequestParam Long deskId,
            @RequestParam String orderlistStatus,
            @RequestParam Long employeeId,
            @RequestParam Long orderlistTotalprice,
            @RequestParam Long storeId) {

        try {
            Long orderId = orderlistService.addorderlist(
                    userId, deskId, orderlistStatus, employeeId, orderlistTotalprice, storeId);
            return String.valueOf(orderId); // 返回订单主键
        } catch (Exception e) {
            return "0"; // 插入失败返回 0，前端据此判断
        }
    }
    
    @RequestMapping("/queryByStoreId")
    public List<Orderlist> queryByStoreId(@RequestParam Long storeId){
        return orderlistService.queryByStoreId(storeId);
    }

    
    /**
     * 更新订单状态
     * @param orderlistId 订单ID
     * @param orderlistStatus 新订单状态
     * @return 操作结果消息，成功返回"更新成功"，失败返回"更新失败"
     */
    @RequestMapping("/updateStatus")
    public String updateStatus(@RequestParam Long orderlistId,
                               @RequestParam String orderlistStatus) {
        try {
            int result = orderlistService.updateStatus(orderlistId, orderlistStatus);
            return result > 0 ? "success" : "fail";
        } catch (Exception e) {
            return "fail";
        }
    }

    
    @RequestMapping("/queryByuserId")
   	public List<Orderlist> queryByuserId(Long userId){
   		return orderlistService.queryByuserId(userId);
   	}
    @GetMapping("/all")
    public Page<Orderlist> all(
            @RequestParam Long storeId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int size
    ) {
        return orderlistService.findPageByStore(storeId, page, size);
    }
    
    @GetMapping("/allformobile")
    public List<Orderlist> all(@RequestParam Long storeId) {
        return orderlistService.findAllByStore(storeId);
    }

    @RequestMapping("/queryById")
    public Orderlist queryById(Long orderlistId) {
        // 调用Service层方法（需在Service和Mapper中实现）
        return orderlistService.queryById(orderlistId);
    }

    @GetMapping("/search")
    public List<Orderlist> search(@RequestParam Long storeId,
                                  @RequestParam String startTime,
                                  @RequestParam String endTime) { 
    	DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    	Timestamp start = Timestamp.valueOf(LocalDateTime.parse(startTime, fmt));
    	Timestamp end   = Timestamp.valueOf(LocalDateTime.parse(endTime, fmt));
        return orderlistService.searchByTime(storeId, start, end);
    }
    @GetMapping("/queryallpriceByDate")
    public Map<String, Object> getTotalPriceByDay(
            @RequestParam("date") 
            @DateTimeFormat(pattern = "yyyy-MM-dd") 
            Date date) {
        
        // 调用Service层方法获取总销售额
        BigDecimal totalPrice = orderlistService.getTotalPriceByDay(date);
        
        // 构建响应结果（使用工具类格式化日期）
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "查询成功");
        result.put("totalprice", totalPrice);
        // 关键修改：返回中国大陆格式日期
        result.put("date", DateFormatUtil.formatChineseDate(date)); 
        
        return result;
    }
    @GetMapping("/getGoodsTotalCountByDay")
    public Map<String, Object> getGoodsTotalCountByDay(
            @RequestParam("date") 
            @DateTimeFormat(pattern = "yyyy-MM-dd") 
            Date date) {
        
        // 调用Service层方法获取商品销售总量统计
        Map<String, Long> goodsCountMap = orderlistService.getGoodsTotalCountByDay(date);
        
        // 构建统一响应格式（使用工具类格式化日期）
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", goodsCountMap.isEmpty() ? "该日期暂无销售数据" : "查询成功");
        result.put("totalGoodsTypes", goodsCountMap.size());
        result.put("data", goodsCountMap);
        // 关键修改：返回中国大陆格式日期
        result.put("queryDate", DateFormatUtil.formatChineseDate(date)); 
        
        return result;
    }
    /**
     * 查询指定日期的所有订单ID、用户ID和员工ID
     */
    @GetMapping("/getOrderIdsByDay")
    public Map<String, Object> getOrderIdsByDay(
            @RequestParam("date") 
            @DateTimeFormat(pattern = "yyyy-MM-dd") 
            Date date) {
        
        // 调用Service层方法获取订单ID列表
        List<Map<String, Long>> orderIdsList = orderlistService.getOrderIdsByDay(date);
        
        // 构建统一响应格式
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", orderIdsList.isEmpty() ? "该日期暂无订单数据" : "查询成功");
        result.put("totalOrders", orderIdsList.size()); // 订单总数
        result.put("data", orderIdsList); // 包含orderlistId、userId、employeeId的列表
        result.put("queryDate", DateFormatUtil.formatChineseDate(date)); // 格式化的查询日期
        
        return result;
    }
}
